package com.zenitera.bigdata.state;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.flink.util.Collector;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

import static org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer.Semantic.EXACTLY_ONCE;

/**
 * Kafka+Flink+Kafka 实现端到端严格一次
 */

public class Flink03_State_End2End {
    public static void main(String[] args) {
        System.setProperty("HADOOP_USER_NAME", "wangting");
        Configuration conf = new Configuration();
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        // 设置并行度
        env.setParallelism(1);
        // 开启checkpoint
        env.enableCheckpointing(2000);
        // 状态后端
        env.setStateBackend(new HashMapStateBackend());
        // checkpoint目录地址
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hdt-dmcp-ops01:8020/ck100");
        // 设置语义
        env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
        // checkpoint并行数量
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(1);
        // checkpoint最小时间间隔
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(800);

        // kafka source 配置
        Properties sourceProps = new Properties();
        sourceProps.put("bootstrap.servers", "hdt-dmcp-ops01:9092,hhdt-dmcp-ops02:9092,hdt-dmcp-ops03:9092");
        sourceProps.put("group.id", "Flink03_State_End2End");

        // 防止重复读取
        sourceProps.put("isolation.level", "read_committed");

        // kafka sink 配置
        Properties sinkProps = new Properties();
        sinkProps.put("bootstrap.servers", "hdt-dmcp-ops01:9092,hhdt-dmcp-ops02:9092,hdt-dmcp-ops03:9092");
        sinkProps.put("transaction.timeout.ms", 15 * 60 * 1000);

        SingleOutputStreamOperator<Tuple2<String, Long>> stream = env
                .addSource(
                        new FlinkKafkaConsumer<String>("s1", new SimpleStringSchema(), sourceProps)
                                .setStartFromLatest()
                )
                .flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public void flatMap(String value, Collector<Tuple2<String, Long>> out) throws Exception {
                        for (String word : value.split(" ")) {
                            out.collect(Tuple2.of(word, 1L));
                        }
                    }
                })
                .keyBy(t -> t.f0)
                .sum(1);
        stream
                .addSink(new FlinkKafkaProducer<Tuple2<String, Long>>(
                        "default",
                        new KafkaSerializationSchema<Tuple2<String, Long>>() {
                            @Override
                            public ProducerRecord<byte[], byte[]> serialize(Tuple2<String, Long> element,
                                                                            @Nullable Long timestamp) {

                                return new ProducerRecord<>("s2", (element.f0 + "_" + element.f1).getBytes(StandardCharsets.UTF_8));
                            }
                        },
                        sinkProps,
                        EXACTLY_ONCE
                ));

        stream.addSink(new SinkFunction<Tuple2<String, Long>>() {
            @Override
            public void invoke(Tuple2<String, Long> value,
                               Context context) throws Exception {
                if (value.f0.contains("x")) {
                    throw new RuntimeException("异常");
                }
            }
        });
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}